<?php
require "domain.php";
require "functions.php";

$tracked_modules = array("assign", "choice", "forum", "resource", "url");

function local_group_created($course)
 {
	global $CFG;
	
	$group = new Group();
	$group->setId("moodle_course_".$course->id);
	$group->setName($course->shortname);
	$group->setObjectType("GROUP");
	
	$post_data = json_encode($group);
	
	$url = $CFG->endpoint."/actor/create";
	
	doPut($url, $post_data);
}

function local_group_deleted($course)
{
	global $CFG;
	$url = $CFG->endpoint."/actor/delete/moodle_course_".$course->id;
	doDelete($url, null);
}

function local_group_viewed($course)
{
	global $USER;

	$verb = getVerb("group_viewed");

	$agent = getAgent($USER->id);

	$group = getGroup($course->courseid);

	sendStatement($agent, $verb, $group, null);
}

function local_agent_created($user)
{
	global $CFG;
	
	$newAgent = new Agent();
	$newAgent->setId("moodle_user_".$user->id);
	$newAgent->setName($user->username);
	$newAgent->setMbox($user->email);
	$newAgent->setObjectType("AGENT");
	
	$post_data = json_encode($newAgent);
	
	$url = $CFG->endpoint."/actor/create";
	
	doPut($url, $post_data);
}

function local_agent_deleted($user)
{
	global $CFG;
	$url = $CFG->endpoint."/actor/delete/moodle_user_".$user->id;
	doDelete($url, null);
}

function local_agent_enrolled($ue)
{
	global $CFG;
	$url = $CFG->endpoint."/actor/addToGroup/moodle_course_".$ue->courseid."/moodle_user_".$ue->userid;
	doPut($url, null);
}

function local_agent_unenrolled($ue)
{
	global $CFG;
	$url = $CFG->endpoint."/actor/removeFromGroup/moodle_course_".$ue->courseid."/moodle_user_".$ue->userid;
	doDelete($url, null);
}

/*Cuando se crea un modulo se llama a esta funcion. Recibe como parametro la info minima del modulo:
 * modulename: nombre del modulo (url, resource, forum, etc)
 * userid: usuario que lo crea
 * courseid: curso al que pertenece
 * cmid: id del modulo. En la tabla mdl_course_modules busco que instancia corresponde al modulo creado (instance)
 * y lo busco en dentro de la tabla que corresponde a ese modulo. Por ejemplo: modulename=url, cmid= 5 significa que dentro de mdl_course_modules busco el registro con id 5.
 * De ese registro me quedo con el valor del campo 'instance'. Ese valor lo uso para buscar dentro de la tabla que corresponde al tipo de modulo, por ejemplo mdl_url con id = instace
 * Con la informacion de mod recupero el verbo (tipomodulo_action, por ejemplo url_viewed), recupero el agente que realiza la accion
 * (la variable $USER contiene el usuario actual), recupero el curso para setearlo en el contexto y recupero el elemento. Todos los elementos
 * (url, resource, foro) comparten algunas caracreristicas que son las q mando (id, name, e intro).
 * Con esos datos creo un statement
 */
function local_mod_created($mod) {
	global $USER;
	
	if(!in_array($mod->modulename, array("assign", "choice", "forum", "resource", "url"))) {
		return;
	}
	
	$verb = getVerb($mod->modulename."_created");
	
	$agent = getAgent($USER->id);
	
	$group = getGroup($mod->courseid);
	
	$modCreated = getElement($mod->modulename, $mod->cmid, true);
	
	$activity = new Activity();
	$activity->setId($mod->modulename."_".$modCreated->id);
	$activity->setDescription($modCreated->intro);
	$activity->setObjectType("ACTIVITY");
	
	if($mod->modulename == "url")
	{
		global $DB;
		$url = $DB->get_record('url', array('id'=>$modCreated->id));
		$activity->setName($url->externalurl);
	}
	else	
		$activity->setName($modCreated->name);
	
	$context = new StatementContext();
	$context->setTeam($group);
	
	sendStatement($agent, $verb, $activity, $context);
}

/*Igual a local_mod_created con la sola diferencia que como ya fue borrado solo puedo mandar el id
 * 
 */
function local_mod_deleted($mod) {
	global $USER;
	
	if(!in_array($mod->modulename, array("assign", "choice", "forum", "resource", "url"))) {
		return;
	}
	
	$verb = getVerb($mod->modulename."_deleted");
	
	$agent = getAgent($USER->id);
	
	$group = getGroup($mod->courseid);
	
	//Solo puedo setear id porque ya fue borrado. En el LRS puedo sacar nombre y descripcion por el verbo y el id.
	//Por ejemplo url_deleted con id de actividad 1 es porque se borro la url 1
	$activity = new Activity();
	$activity->setId($mod->modulename."_".$mod->courseid);
	$activity->setObjectType("ACTIVITY");
	
	$context = new StatementContext();
	$context->setTeam($group);
	
	$response = sendStatement($agent, $verb, $activity, $context);
}

/*Cuando cualquier evento que no sea crear o borrar se produce sobre los elementos a los cuales les definidos un observer
 * se llama a esta funcion. Recibe en eventdata la informacion del evento (https://docs.moodle.org/dev/Event_2#Information_contained_in_events)
 * Con la informacion de eventdata recupero el verbo (tipomodulo_action, por ejemplo url_viewed), recupero el agente que realiza la accion
 * (la variable $USER contiene el usuario actual), recupero el curso para setearlo en el contexto y recupero el elemento. Todos los elementos
 * (url, resource, foro) comparten algunas caracreristicas que son las q mando (id, name, e intro).
 * Con esos datos creo un statement
 */ 
function local_event($eventdata) {
	global $USER;
	
	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));
	
	$agent = getAgent($USER->id);
	
	$group = getGroup($eventdata->courseid);
	
	$elementViewed = getElement($eventdata->objecttable, $eventdata->objectid, false);
	
	$activity = new Activity();
	$activity->setId($eventdata->objecttable."_".$elementViewed->id);
	$activity->setName($elementViewed->name);
	$activity->setDescription($elementViewed->intro);
	$activity->setObjectType("ACTIVITY");
	
	$context = new StatementContext();
	$context->setTeam($group);
	
	$response = sendStatement($agent, $verb, $activity, $context);
}

//Para los eventos relacionados con las tareas
function local_assing_event($eventdata) {
	global $USER;

	$assign = $eventdata->get_assign()->get_instance();
	
	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));

	$agent = getAgent($USER->id);

	$group = getGroup($assign->course);

	$activity = new Activity();
	$activity->setId("assign_".$assign->id);
	$activity->setName($assign->name);
	$activity->setDescription($assign->intro);
	$activity->setObjectType("ACTIVITY");

	$context = new StatementContext();
	$context->setTeam($group);

	$response = sendStatement($agent, $verb, $activity, $context);
}

//Para los eventos relacionados con los archivos de entrega de las tareas
function local_assignsubmission_file_event($eventdata) {
	global $USER;
DIE("local_assignsubmission_file_event".son_encode($eventdata));
	$assign = $eventdata->get_assign()->get_instance();

	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));

	$agent = getAgent($USER->id);

	$group = getGroup($assign->course);

	$activity = new Activity();
	$activity->setId($eventdata->component."_".$assign->id);
	$activity->setName($assign->name);
	$activity->setDescription($assign->intro);
	$activity->setObjectType("ACTIVITY");

	$context = new StatementContext();
	$context->setTeam($group);

	$response = sendStatement($agent, $verb, $activity, $context);
}

//Para los eventos relacionados con los archivos de los foros
function local_forum_file_event($eventdata) {
	global $USER;
	
	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));

	$agent = getAgent($USER->id);

	$group = getGroup($eventdata->courseid);
	
	$forum = getElement($eventdata->objecttable, $eventdata->objectid, false);

	$activity = new Activity();
	$activity->setObjectType("ACTIVITY");
	
	$activity->setId($eventdata->objecttable."_".$forum->id);
	$activity->setName($forum->subject);
	$activity->setDescription($forum->message);
	
	$context = new StatementContext();
	$context->setTeam($group);
	
	$attachments = null;
	
	if($eventdata->action == "uploaded")
	{
		global $DB;
		global $CFG;
		$table = "files";
		$select = "component = 'mod_forum' AND filearea = 'attachment' AND filesize <> 0 AND itemid = ".$forum->id;
		$result = $DB->get_record_select($table, $select, null, "*", IGNORE_MISSING);
		if($result)
		{
			$attachment = new Attachment($eventdata->objecttable."_file_".$result->id, $result->filename, $result->filename, $result->filesize, $CFG->wwwroot."/pluginfile.php/".$result->contextid."/mod_forum/attachment/".$forum->id."/".$result->filename, "url");
			$attachments = array($attachment);
		}
	}

	sendStatement($agent, $verb, $activity, $context, $attachments);
}

//Para los eventos relacionados a las discusiones de un foro
function local_discussion_event($eventdata) {
	global $USER;

	$data = $eventdata->get_data();
		
	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));
	
	$agent = getAgent($USER->id);
	
	$group = getGroup($eventdata->courseid);
	
	$activity = new Activity();
	
	if($data["action"] != "deleted")
	{
		$discussion = getElement($eventdata->objecttable, $eventdata->objectid, false);
		$forum = getElement("forum", $discussion->forum, false);
		$activity->setId($eventdata->objecttable."_".$discussion->id);
		$activity->setName($discussion->name);
		$activity->setDescription($forum->name);
	}
	else
		$activity->setId($eventdata->objectid);
		
	$activity->setObjectType("ACTIVITY");
		
	$context = new StatementContext();
	$context->setTeam($group);
	
	$response = sendStatement($agent, $verb, $activity, $context);
}


//Para los eventos relacionados a los comentarios de un foro
function local_post_event($eventdata) {
	global $USER;

	$data = $eventdata->get_data();
	
	$verb = getVerb(str_replace("mod_","",$eventdata->component."_".$eventdata->action));
	
	$agent = getAgent($USER->id);
	
	$group = getGroup($eventdata->courseid);
	
	$activity = new Activity();
	
	if($data["action"] != "deleted")
	{
		$post = getElement($eventdata->objecttable, $eventdata->objectid, false);
		$discussion = getElement("forum_discussions", $post->discussion, false);
		$forum = getElement("forum", $discussion->forum, false);
		
		$activity->setId($eventdata->objecttable."_".$post->id);
		$activity->setName($post->subject." - ".$discussion->name." - ".$forum->name);
		$activity->setDescription($post->message);
	}
	else
		$activity->setId($eventdata->objectid);
	
	$activity->setObjectType("ACTIVITY");
	
	$context = new StatementContext();
	$context->setTeam($group);
	
	$response = sendStatement($agent, $verb, $activity, $context);
}
?>